package com.itheima.entity;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.google.common.collect.Lists;
import com.itheima.service.UserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import java.util.List;

/**
 * @Description: 解析监听器
 */
@Data
@Slf4j
public class ExcelListener extends AnalysisEventListener {

    private UserService userService;

    public ExcelListener(UserService userService) {
        this.userService = userService;
    }

    /** Excel数据暂存区*/
    private List<ExcelModel> datas = Lists.newArrayList();

    @Override /** 每解析一行Excel会回调invoke()方法 */
    public void invoke(Object object, AnalysisContext analysisContext) {
        ExcelModel excelModel = (ExcelModel)object;
        datas.add(excelModel);
    }


    @Override /** 整个excel解析结束会执行doAfterAllAnalysed()方法 */
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        try { // 调用业务层入库
            if(!ObjectUtils.isEmpty(datas)){
                userService.batchInsert(datas);
            }
        } catch (Exception e) {
           log.error("批量导入失败",e);
        }
        datas.clear();
    }
}
